<template>
  <view class="image-upload-page p_bg_f3">
    <view class="image-upload-page--content">
      <view class="image-list" :class="{ horizontal: checked }">
        <view class="image-item upload-btn" @click="handleUpload">
          <view class="plus"></view>
          <view class="name">添加图片</view>
        </view>
        <view v-for="(item, index) in fileList" :key="index" class="image-item">
          <view class="remove-btn" @click="remove(index)"></view>
          <image :src="item.url" mode="aspectFit" :class="{ rotate: item.flag !== checked }"></image>
          <view class="btns">
            <view class="btn" @click="move('up', index)">上移</view>
            <view class="btn" @click="move('down', index)">下移</view>
            <view class="btn" @click="edit(index)">编辑</view>
          </view>
        </view>
      </view>
      <view class="prompt">
        <view class="txt">
          <text>打印文件默认为左侧翻页</text>
        </view>
        <view class="txt">
          <text>请点击下方纵向/横向按钮</text>
        </view>
        <view class="txt">
          <text>将图片旋转至正常阅读方向</text>
        </view>
        <view class="txt">
          <text>图片打印四周会有白边</text>
        </view>
      </view>
    </view>
    <view class="image-upload-page--bottom">
      <view class="image-upload-page--bottom__left">
        <switch :checked="checked" color="#05B570" style="transform: scale(1);transform-origin: left center;" @change="updateChecked" />
        <text class="name">{{checked ? '横向' : '纵向'}}</text>
        <view class="prompt" @click="viewPrompt">?</view>
      </view>
      <view class="submit-btn" @click="handleSubmit">确定</view>
    </view>
  </view>
</template>

<script>
  import MultipleUpload from '@/utils/upload.js';
  const app = getApp();
  
  export default {
    data() {
      return {
        totalMax: 50,
        singleMax: 9,
        fileList: [],
        checked: false
      };
    },
    onShow() {
      const target = app.getActiveImage();
      if (target) {
        uni.getImageInfo({
          src: target.url,
          success: (res) => {
            this.fileList[target.index].url = target.url;
            this.fileList[target.index].flag = res.width / res.height <= 1 ? false : true;
            app.setActiveImage(null);
          }
        })
      }
    },
    onUnload() {
      app.setActiveImage(null);
    },
    methods: {
      handleUpload() {
        const count = Math.min(this.totalMax - this.fileList.length, this.singleMax);
        if (count === 0) {
          uni.showModal({
            title: '图片上传提示',
            content: `单次最多上传${this.totalMax}张图片，您可以先点击右下角确定按钮上传本批图片，然后再次点击图片上传按钮继续上传~`,
            showCancel: false,
            confirmText: '知道了'
          })
        }
        uni.chooseImage({
          count,
          sizeType: ['original'],
          success: (res) => {
            uni.showLoading({
              title: '读取中',
              mask: true
            })
            const urls = Array.from({ length: res.tempFilePaths.length }, () => null);
            res.tempFilePaths.forEach((v, i) => {
              uni.getImageInfo({
                src: v,
                success: (res) => {
                  urls[i] = {
                    orgFile: v,
                    url: v,
                    flag: res.width / res.height <= 1 ? false : true
                  }
                  if (urls.every(u => u !== null)) {
                    uni.hideLoading();
                    this.fileList.push(...urls);
                  }
                }
              })
            });
          }
        })
      },
      updateChecked() {
        this.checked = !this.checked;
      },
      viewPrompt() {
        uni.showModal({
          content: '纵向采用长边翻页\r\n横向采用短边翻页',
          showCancel: false
        })
      },
      // 删除
      remove(idx) {
        this.fileList = this.fileList.filter((v, i) => i !== idx);
      },
      // 移动
      move(t, idx) {
        if (t === 'up') {
          // 上移
          if (idx > 0) {
            const tempObj = {
              orgFile: this.fileList[idx].orgFile,
              url: this.fileList[idx].url,
              flag: this.fileList[idx].flag
            }
            this.fileList[idx].orgFile = this.fileList[idx - 1].orgFile;
            this.fileList[idx].url = this.fileList[idx - 1].url;
            this.fileList[idx].flag = this.fileList[idx - 1].flag;
            this.fileList[idx - 1].orgFile = tempObj.orgFile;
            this.fileList[idx - 1].url = tempObj.url;
            this.fileList[idx - 1].flag = tempObj.flag;
          }
        } else {
          // 下移
          if (idx < this.fileList.length - 1) {
            const tempObj = {
              orgFile: this.fileList[idx].orgFile,
              url: this.fileList[idx].url,
              flag: this.fileList[idx].flag,
            }
            this.fileList[idx].orgFile = this.fileList[idx + 1].orgFile;
            this.fileList[idx].url = this.fileList[idx + 1].url;
            this.fileList[idx].flag = this.fileList[idx + 1].flag;
            this.fileList[idx + 1].orgFile = tempObj.orgFile;
            this.fileList[idx + 1].url = tempObj.url;
            this.fileList[idx + 1].flag = tempObj.flag;
          }
        }
      },
      // 编辑
      edit(idx) {
        const target = this.fileList.find((v, i) => i === idx);
        app.setActiveImage({
          index: idx,
          url: target.url,
          orgFile: target.orgFile,
          flag: target.flag
        });
        uni.navigateTo({
          url: 'imageUploadEdit?direction=' + (this.checked ? 'landscape' : 'portrait')
        })
      },
      // 确定
      handleSubmit() {
        if (this.fileList.length === 0) {
          uni.showToast({
            title: '请添加至少一张图片',
            icon: 'none'
          })
          return;
        }
        const urls = Array.from({ length: this.fileList.length }, () => null);
        MultipleUpload(this.fileList.reduce((a,v) => [...a, v.url], []), (url, flag, idx) => {
          if (url !== '') {
            urls[idx] = url;
          }
          if (flag) {
            const params = { 
              images: urls.join(','),
              direction: this.checked ? 'landscape' : 'portrait'
            };
            uni.showLoading({
              title: '生成中',
              mask: true
            })
            this.$http.post(this.$api.image_pdf, params, false, true).then((res) => {
              uni.hideLoading();
              const curDate = new Date();
              const month = curDate.getMonth() + 1;
              const date = curDate.getDate();
              const h = curDate.getHours();
              const m = curDate.getMinutes();
              const s = curDate.getSeconds();
              this.$http.post(this.$api.cartAdd, {
                file: res.data.pdf_url,
                name: `${urls.length}张图片-${this.renderTime(month)}-${this.renderTime(date)} ${this.renderTime(h)}:${this.renderTime(m)}:${this.renderTime(s)}.pdf`
              }).then(() => {
                uni.navigateBack({
                  success() {
                    setTimeout(() => {
                      const pages = getCurrentPages();
                      const vm = pages[pages.length - 1];
                      vm.$vm.getListData();
                    }, 300)
                  }
                });
              }).catch(() => {});
            }).catch((err) => {
              uni.hideLoading();
            });
          }
        })
      },
      // 格式化时间
      renderTime(d) {
        return d < 10 ? '0' + d : d;
      }
    }
  }
</script>

<style lang="scss">
.image-upload-page {
  min-height: 100vh;
  width: 100vw;
  &--content {
    padding-bottom: calc(60px + env(safe-area-inset-bottom));
    box-sizing: border-box;
    overflow: hidden;
    .image-list {
      @include flex(row,flex-start,flex-start,wrap);
      overflow: hidden;
      &.horizontal {
        .image-item {
          height: calc((375rpx - 24px) / 1.4);
          image {
            width: calc(375rpx - 24px);
            height: calc((375rpx - 24px) / 1.4);
            &.rotate {
              height: calc(375rpx - 24px);
              width: calc((375rpx - 24px) / 1.4);
            }
          }
        }
      }
      .image-item {
        width: calc(375rpx - 24px);
        height: calc((375rpx - 24px) * 1.4);
        margin: 12px;
        background-color: #fff;
        box-sizing: border-box;
        border: 1px solid #ddd;
        position: relative;
        overflow: hidden;
        &.upload-btn {
          @include flex(column);
          .plus {
            position: relative;
            width: 44px;
            height: 44px;
            margin-bottom: 10px;
            &::before {
              content: '';
              width: 100%;
              height: 4px;
              background-color: #ccc;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
            &::after {
              content: '';
              width: 4px;
              height: 100%;
              background-color: #ccc;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
          }
          .name {
            font-size: 14px;
            color: #888;
          }
        }
        .remove-btn {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          position: absolute;
          top: 5px;
          right: 5px;
          background: rgba(#000, .3);
          transform: rotate(45deg);
          transform-origin: center center;
          z-index: 3;
          &::before {
            content: '';
            width: 50%;
            height: 2px;
            background-color: #fff;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
          }
          &::after {
            content: '';
            width: 2px;
            height: 50%;
            background-color: #fff;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
          }
        }
        .btns {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          box-sizing: border-box;
          padding: 0 5px 5px;
          @include flex(row,center,space-between);
          .btn {
            height: 24px;
            line-height: 24px;
            background-color: rgba(#000, .3);
            font-size: 14px;
            color: #fff;
            padding: 0 8px;
            border-radius: 5px;
          }
        }
        image {
          display: block;
          width: calc(375rpx - 24px);
          height: calc((375rpx - 24px) * 1.4);
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          &.rotate {
            transform:  translate(-50%, -50%) rotate(-90deg);
            height: calc(375rpx - 24px);
            width: calc((375rpx - 24px) * 1.4);
          }
        }
      }
    }
    .prompt {
      text-align: center;
      font-size: 14px;
      color: #888;
      line-height: 1.5;
      padding-bottom: 32px;
    }
  }
  &--bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    box-sizing: border-box;
    box-shadow: 0 -1px 5px rgba(#000,.1);
    background-color: #fff;
    @include flex(row,center,space-between);
    padding-left: 12px;
    padding-right: 12px;
    padding-bottom: env(safe-area-inset-bottom);
    &__left {
      @include flex;
      font-size: 14px;
      .prompt {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        overflow: hidden;
        font-size: 12px;
        color: #fff;
        background-color: $uni-color-warning;
        @include flex;
        margin-left: 4px;
      }
    }
    .submit-btn {
      margin: 12px 0;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      color: #fff;
      padding: 0 24px;
      border-radius: 20px;
      @include flex;
      background-color: $uni-color-primary;
      letter-spacing: 2px;
    }
  }
}
</style>
